<template>
  <page-wrap
    :title="' '"
    txtColor="#222"
    :showTop="showTop"
    :dark="true"
    back
    hideTab
  >
    <view
      class="password-strengthen-container"
      :style="'padding-top:' + navHeight + 'px;'"
    >
      <view class="text1"> 密码强化 </view>
      <view class="text2">您的密码存在安全风险，请修改密码以保护您的账户 </view>
      <view class="text3">登陆账号：{{ encryptionPhone }} </view>

      <view class="password-input">
        <input
          v-if="form.pswType == 'password'"
          class="input"
          :maxlength="inputMaxLength"
          v-model="form.password"
          placeholder="密码"
          placeholder-style="color: #bbbbbb;"
          type="password"
          :clearable="false"
          :adjust-position="false"
          label-width="0"
        />
        <input
          v-else
          class="input"
          :maxlength="inputMaxLength"
          v-model="form.password"
          placeholder="密码"
          placeholder-style="color: #bbbbbb;"
          type="text"
          :clearable="false"
          :adjust-position="false"
          label-width="0"
        />
        <view class="eye-wrap" @click="handleShowPsw">
          <text :class="['show-psw', form.pswType]"></text>
        </view>
      </view>

      <view class="normal-line"> </view>
      <view class="password-input">
        <input
          v-if="form.confirmPswType == 'password'"
          class="input"
          :maxlength="inputMaxLength"
          v-model="form.confirmPassword"
          placeholder="确认密码"
          placeholder-style="color: #bbbbbb;"
          type="password"
          :clearable="false"
          :adjust-position="false"
          label-width="0"
        />
        <input
          v-else
          class="input"
          :maxlength="inputMaxLength"
          v-model="form.confirmPassword"
          placeholder="确认密码"
          placeholder-style="color: #bbbbbb;"
          type="text"
          :clearable="false"
          :adjust-position="false"
          label-width="0"
        />
        <view class="eye-wrap" @click="handleShowConfirmPswType">
          <text :class="['show-psw', form.confirmPswType]"></text>
        </view>
      </view>
      <view class="normal-line"> </view>

      <view class="strength-line">
        <view class="strength-left-text"> 密码强度：</view>

        <view
          class="strength-right"
          :style="{ width: strengthRightWidth + 'px' }"
        >
          <view class="strength-items">
            <view
              v-for="(item, index) in strengthLink"
              :key="index"
              class="item"
              :style="{
                background:
                  (index <= currentStrength && currentStrength >= 0)
                    ? strengthLink[currentStrength].color
                    : '#F3F3F3',
                width: itemWidthPx + 'px',
                marginRight: itemMarginRightPx + 'px',
              }"
            >
            </view>
          </view>
          <view
            class="strength-text"
            :style="{
              color:currentStrengthColor,
            }"
          >
            {{  currentStrengthText }}
          </view>
        </view>
      </view>
      <view class="left-text"> 密码需要满足以下要求： </view>
      <view class="require-container">
        <view class="check-container">
          <image
            class="check-container"
            :src="isRule1 ? iconSelected : iconNotSelect"
          ></image>
        </view>
        <view>至少8个字符 </view>
      </view>
      <view class="require-container">
        <view class="check-container">
          <image
            class="check-container"
            :src="isRule2 ? iconSelected : iconNotSelect"
          ></image>
        </view>
        <view> 至少含字母和数字，不能包含空格 </view>
      </view>
      <view
        @click="handleCommit"
        class="commit-btn"
        :style="{ background: canCommit ? '#F04646' : '#FE9390' }"
      >
        确认
      </view>
      <view class="cancel-btn">
        <span @click="handleCancel"> 取消 </span>
      </view>

      <u-popup
        v-model="showPopup"
        @close="handleClosePop"
        mode="center"
        width="91%"
        closeable
      >
        <view class="pop-container">
          <view class="pop-text1">
            若您的手机号：
            {{ encryptionPhone }} 现在可接收短信，请点击获取验证码
          </view>

          <view class="picture-code-line">
            <input
              v-model="captchaCode"
              type="text"
              maxlength="8"
              placeholder="请输入图形验证码"
            />
            <view class="right-img">
              <image
                style="width: 80px; height: 26px"
                :src="captchPicture + captchaId"
                @click="getCaptchImg"
              ></image>
            </view>
          </view>
          <view class="pop-normal-line"> </view>

          <view class="sms-code-line">
            <input
              v-model="verificationCode"
              type="number"
              maxlength="8"
              placeholder="请输入短信验证码"
            />
            <view class="get-sms-text" @click="handleSendCode">
              {{ target.codeText }}
            </view>
          </view>
          <view class="pop-normal-line"> </view>

          <view class="pop-text2">
            手机号无法使用？<span
              :style="{ color: '#F04646' }"
              @click="handleAppeal"
            >
              立即申诉
            </span>
          </view>

          <view
            class="pop-commit"
            :style="{
              background: canResetPasswordCommit ? '#F04646' : '#FE9390',
            }"
            @click="handleResetPassword"
          >
            确认
          </view>
        </view>
      </u-popup>
    </view>

    
  </page-wrap>
</template>
  
  <script>
import {
  captchaInit,
  sendLoginCode,
  checkUnameCanReg,
  strengthenPassword,
} from "@/api/index"; 
import { apiClusterJava } from "@/api/root";
import { checkPhoneValid, showDelayToastTip } from "@/utils/handle";
export default {
  mixins: [],
  components: {
    
  },
  data() {
    return {
      form: {
        password: null,
        pswType: "password",

        confirmPassword: null,
        confirmPswType: "password",
      },

      inputMaxLength : 20,
      captchaCode: "", // 图形验证码
      verificationCode: "", // 短信或者电子邮箱验证码
      navHeight: getApp().globalData.navHeight,

      showPopup: false,
      strengthRightWidth: 0,
      itemWidthPx: 0,
      itemMarginRightPx: 0,

      iconNotSelect:
        "//img3.job1001.com/ypMp/elan/images/password/icon_not_select.png",

      iconSelected:
        "//img3.job1001.com/ypMp/elan/images/password/icon_selected.png",

      captchaId: "",
      captchPicture: "",
      canCommit: false,
      canResetPasswordCommit: false,
      isRule1: false,
      isRule2: false,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      phone: "", // 手机号
      encryptionPhone: "", // 加星号 的手机号
      target: {
        codeText: "获取验证码",
        codeTimer: null,
      },
      currentStrength: -1,
      currentStrengthColor:"#F3F3F3",
      currentStrengthText:"",
      strengthLink: [
        {
          name: "弱",
          color: "#F04646",
        },
        {
          name: "中",
          color: "#FF9539",
        },
        {
          name: "强",
          color: "#00D29A",
        },
      ],
    };
  },
  watch: {
    verificationCode: {
      handler(val) {
        this.canResetPasswordCommit = this.verificationCode && this.captchaCode;
      },
      deep: true,
    },
    captchaCode: {
      handler(val) {
        this.canResetPasswordCommit = this.verificationCode && this.captchaCode;
      },
      deep: true,
    },
    form: {
      handler(val) {
        this.checkKeyword();
      },
      deep: true,
    },
  },
  onLoad(options) {
    this.phone = options && options.phone ? options.phone : "";
    this.encryptionPhone = this.maskPhoneNumber(this.phone);
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {},
  onShow() {},
  created() {},
  mounted() {
    this.encryptionPhone = this.maskPhoneNumber(this.phone);
    this.captchPicture = apiClusterJava + "/api-auth/common/captcha/draw/";
    this.getCaptchImg();
    this.calculateItemParams();
  },
  unmounted() {
    if (this.target.codeTimer) {
      clearInterval(this.target.codeTimer);
    }
  },
  methods: {
    // 切换密码显示隐藏状态
    handleShowPsw() {
      let data = this.form.pswType === "password" ? "text" : "password";
      this.$set(this.form, "pswType", data);
    },

    handleShowConfirmPswType() {
      let data = this.form.confirmPswType === "password" ? "text" : "password";
      this.$set(this.form, "confirmPswType", data);
    },

    handleResetPassword() {
      uni.showLoading();
      var conditionArr = JSON.stringify({
        uname: this.phone,
        password: this.form.password,
        code: this.verificationCode,
      });
      strengthenPassword({ conditionArr: conditionArr })
        .then((res) => {
          uni.hideLoading();
          if (res && res.code == 200) {
            showDelayToastTip("重置密码成功", 200);
            setTimeout(() => {
              uni.navigateBack({ delta: 1 });
            }, 300);
          } else {
            if (res && res.status_desc) {
              showDelayToastTip(res.status_desc, 200);
            }
          }
        })
        .catch(() => {
          uni.hideLoading();
        });
    },

    maskPhoneNumber(phoneNumber) {
      return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },

    handleCheckPhone(uname, callback) {
      if (!uname) {
        return uni.showToast({ icon: "none", title: "请输入手机号" });
      }
      if (!checkPhoneValid(uname)) {
        return uni.showToast({ icon: "none", title: "请输入正确手机号" });
      }
      uni.showLoading();
      checkUnameCanReg({ uname })
        .then((res) => {
          uni.hideLoading();
          if (callback) callback(res);
        })
        .catch(() => {
          uni.hideLoading();
        });
    },
    // 点击立刻申述
    handleAppeal() {
      return showDelayToastTip("请联系客服热线：0755-86153516", 0);
    },

    handleClosePop() {
      this.showPopup = false;
    },

    calculateItemParams() {
      var that = this;
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".strength-left-text")
          .boundingClientRect((data) => {
            let sys = uni.getSystemInfoSync();
            sys.screenWidth;
            that.itemMarginRightPx = 10;
            that.strengthRightWidth =
              sys.screenWidth - data.width - uni.upx2px(54 * 2);
            that.itemWidthPx =
              (that.strengthRightWidth - that.itemMarginRightPx * 2) / 3;
          })
          .exec();
      }, 200);
    },

    // 判断字符串是否只有一种字符类型
    isMonoType(str) {
      // 使用正则表达式匹配字符串中的字符类型
      // \w 匹配任意字母数字下划线字符，等价于 [A-Za-z0-9_]
      // \W 匹配任意非单词字符
      // \s 匹配任意空白字符，包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v\u00A0\u2028\u2029]
      // \S 匹配任意非空白字符
      // \d 匹配任意数字，等价于 [0-9]
      // \D 匹配任意非数字
      const regex =
        /^(\w)\1*$|^(\W)\1*$|^(\s)\1*$|^(\S)\1*$|^(\d)\1*$|^(\D)\1*$/;
      return regex.test(str);
    },

    // 判断字符串是否至少含有 字母和数字
    containsLetterAndNumber(str) {
      return /[A-Za-z]/.test(str) && /\d/.test(str);
    },

    // 判断字符串至少要包含 数字， 大写字母，小写字母 这3种类型
    isStrongPassword(str) {
      return /[a-z]/.test(str) && /\d/.test(str) && /[A-Z]/.test(str);
    },
    getCaptchImg() {
      captchaInit().then((res) => {
        this.captchaId = res.data;
      });
    },

    // 发送短信验证码
    handleSendCode() {
      if (this.target.codeTimer) return;
      this.handleCheckPhone(this.phone, (checkRes) => {
        if (checkRes.data) {
          return showDelayToastTip("该手机未注册", 0);
        }

        if (!this.captchaCode) {
          return showDelayToastTip("请输入图形验证码", 0);
        }
        sendLoginCode({
          mobile: this.phone,
          code: this.captchaCode,
          captchaId: this.captchaId,
        })
          .then((res) => {
            uni.showToast({ icon: "none", title: res.status_desc });
            if (res.status === "OK") {
              let sec = 60;
              this.$set(this.target, "codeText", `${--sec} s`);
              this.target.codeTimer = setInterval(() => {
                this.$set(this.target, "codeText", `${--sec} s`);
                if (sec < 1) {
                  clearInterval(this.target.codeTimer);
                  this.$set(this.target, "codeTimer", null);
                  this.$set(this.target, "codeText", "获取验证码");
                }
              }, 1000);
            }
          })
          .catch(() => {
            this.getCaptchImg();
          });
      });
    },
    handleCancel() {
      uni.navigateBack({ delta: 1 });
    },
    handleCommit() {
      if (!this.canCommit) {
        return;
      }
      if (this.form.password != this.form.confirmPassword) {
        showDelayToastTip("两次密码不一样，请重新输入", 0);
        return;
      }
      this.showPopup = true;
      // this.$refs.resumeDeliverDialog.setVisibility(true);
    },

    checkStrength() {
      /**
       * 密码强度校验规则 
       * */
      if(!this.form.password){
        this.currentStrength = -1;
        this.currentStrengthColor = "#F3F3F3";
        this.currentStrengthText = "";
        return;
      }

      if ((this.form.password + "").length < 8 ||
        this.isMonoType(this.form.password)
      ) {
        /**弱密码：
密码长度少于8个字符。
或者密码只包含一种字符类型（例如，全部是字母或者全部是数字）。*/
        this.currentStrength = 0;
        
        this.currentStrengthColor = "#F04646";
        this.currentStrengthText = "弱";
        return;
      }

      if (
        (this.form.password + "").length >= 8 &&
        (this.form.password + "").length <= 11 &&
        this.containsLetterAndNumber(this.form.password)
      ) {
        /**
 * 中等密码：
密码长度在8到11个字符之间。
密码包含两种字符类型（字母和数字）。
*/
        this.currentStrength = 1;
        this.currentStrengthColor = "#FF9539";
        this.currentStrengthText = "中";
        return;
      }

      /**
       * 
强密码：
密码长度12个字符以上。
密码包含3种字符类型（大写字母、小写字母、数字）。
      */
      if (
        (this.form.password + "").length > 12 &&
        this.isStrongPassword(this.form.password)
      ) {
        this.currentStrength = 2;
        this.currentStrengthColor = "#00D29A";
        this.currentStrengthText = "强";
        return;
      }
    },

    checkKeyword() {
      
      this.isRule1 =
        this.form.password && (this.form.password + "").length >= 8;
      this.isRule2 =
        this.form.password &&
        /[A-Za-z]/.test(this.form.password) &&
        /\d/.test(this.form.password) &&
        !this.form.password.includes(" ");
      this.canCommit = this.isRule1 && this.isRule2;
      this.checkStrength();
    },
  },
};
</script>
  
  <style lang="scss">
$img-base-login: $img-base + "login/";
.pop-container {
  padding-left: 32rpx;
  padding-right: 32rpx;
  .pop-text1 {
    font-weight: 400;
    font-size: 28rpx;
    color: #222222;
    margin-top: 80rpx;
  }
  .picture-code-line {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    height: 96rpx;
    .right-img {
    }
  }
  .sms-code-line {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    height: 96rpx;
    .get-sms-text {
      font-weight: 500;
      font-size: 28rpx;
      color: #555555;
    }
  }
  .pop-text2 {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    font-weight: 400;
    font-size: 24rpx;
    color: #555555;
    margin-top: 32rpx;
  }

  .pop-commit {
    margin-top: 32rpx;
    margin-bottom: 64rpx;
    cursor: pointer;
    font-weight: 400;
    font-size: 32rpx;
    color: #ffffff;
    width: 100%;
    height: 88rpx;
    //background: #fe9390;
    border-radius: 10rpx;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .pop-normal-line {
    width: 100%;
    height: 1rpx;
    background: #eeeeee;
  }
}

.form {
  width: 100%;
  .u-form-item {
    padding: 0 !important;
  }

  .u-input__input {
    height: 100rpx;
    color: #222 !important;

    font-size: 28rpx !important;
  }
}

.password-strengthen-container {
  padding-left: 54rpx;
  padding-right: 54rpx;

  .password-input {
    height: 100rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    .input {
      flex-grow: 1;
      height: 100rpx;
    }
  }

  .eye-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80rpx;
    height: 80rpx;
    margin-top: -32rpx;
    margin-bottom: -32rpx;
  }

  .show-psw {
    display: block;
    width: 48rpx;
    height: 48rpx;
    background-image: url($img-base-login + "eye.png");
    background-size: 100% 100%;

    &.password {
      background-image: url($img-base-login + "eyeoff.png");
    }
  }

  .text1 {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    font-size: 56rpx;
    color: #222222;
    margin-top: 196rpx;
  }

  .text2 {
    font-weight: 400;
    font-size: 28rpx;
    color: #555555;
    margin-top: 64rpx;
  }
  .text3 {
    font-weight: 400;
    font-size: 28rpx;
    color: #555555;
    margin-top: 24rpx;
  }

  .normal-line {
    width: 100%;
    height: 1rpx;
    background: #eeeeee;
  }

  .strength-line {
    margin-top: 32rpx;
    margin-bottom: 28rpx;
    display: flex;
    flex-direction: row;

    .strength-right {
      .strength-items {
        display: flex;
        flex-direction: row;
        margin-top: 15rpx;
        .item {
          height: 6rpx;
          margin-right: 16rpx;
        }
      }
      .strength-text {
        font-weight: 400;
        font-size: 24rpx;
      }
    }
  }

  .strength-left-text {
    font-weight: 400;
    font-size: 28rpx;
    color: #555555;
  }

  .left-text {
    font-weight: 400;
    font-size: 28rpx;
    color: #555555;
  }

  .require-container {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-weight: 400;
    font-size: 24rpx;
    color: #bbbbbb;
    margin-top: 24rpx;
    .check-container {
      width: 30rpx;
      height: 30rpx;
      margin-right: 17rpx;
    }
  }

  .commit-btn {
    height: 88rpx;
    // background: #fe9390;
    border-radius: 10rpx;
    font-weight: 400;
    font-size: 32rpx;
    color: #ffffff;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin-top: 64rpx;
  }
  .cancel-btn {
    height: 88rpx;
    // background: #fe9390;
    // border-radius: 10rpx;
    font-weight: 400;
    font-size: 32rpx;
    color: #0271fe;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin-top: 10rpx;
  }
}
</style>
  